import {
  Tabs,
  Row,
  Col
} from 'antd';
import {
  WeaErrorPage,
  WeaTools,
  WeaTableEdit,
  WeaSearchGroup,
  WeaRightMenu,
  WeaFormItem,
  WeaTab,
  WeaNewScroll,
  WeaAlertPage,
  WeaAvatar 
} from 'ecCom'
import isEmpty from 'lodash/isEmpty'
import * as mobx from 'mobx';
import {
  inject,
  observer
} from 'mobx-react';
import SystemCard from './SystemCard';
import PortraitSetting from './PortraitSetting';
import {
  routerShape
} from 'react-router';
import '../../style/card.less';
const toJS = mobx.toJS;
import {
  WeaPopoverHrm
} from 'ecCom';
import TopButton from '../../coms/topButton';
import {i18n} from '../../public/i18n';

const { ua } = WeaTools;
const isIE9 = ua.browser === "IE"

@inject('hrmCard')
@observer
class Main extends React.Component {
  static contextTypes = {
    router: routerShape,
  }
  constructor(props) {
    super(props);
    this.state = {
      weaWorkplanLoaded:false,
      rightMenu: []
    }
  }

  getkey(path) {
    return path.match(/hrm\/card\/\w+/)[0].split('/')[2] || '';
  }
  componentWillReceiveProps(nextProps) {
    const key = this.getkey(nextProps.location.pathname);
    if (this.props.location.key !== nextProps.location.key && key == 'cardInfo') {
      this.init(nextProps);
    }
  }

  componentWillMount() {
    // 异步加载日程模块静态资源
    eventRegister.loadModule('f_workplan', ()=> {
      this.setState({weaWorkplanLoaded:true});
    }, ()=> {});
  }

  componentDidMount() {
    this.init();
  }

  init = (nextProps) => {
    const {
      hrmCard
    } = nextProps || this.props;
    const {
      pathname
    } = (nextProps || this.props).location;
    const key = this.getkey(pathname);
    const hrmId = (nextProps || this.props).params.hrmId || '';
    //const hrmId = pathname.match(/cardInfo\/\w+/)[0].split('/')[1]
    hrmCard.init(key);
    hrmCard.verifyIsAdmin({
      id: hrmId
    });
    hrmCard.getData({
      id: hrmId
    });
  }

  setParentRightMenu = rightMenu => this.setState({rightMenu})

  getTabChildren() {
    const {
      hrmCard,
      children
    } = this.props;
    let {
      tabInfo,
      tabKey,
    } = hrmCard;
    let isIframe = false;
    let ifame;
    let innerPage = false;
    if (window.location.href.indexOf("/spa/hrm/index_mobx.html") == -1) {
      innerPage = true;
    }
    tabInfo = toJS(tabInfo);
    tabInfo && tabInfo.forEach((t) => {
      if (tabKey === t.key) {
        if (t.isIframe) {
          isIframe = true;
          if(t.key == 'iframe-9-workplansearch'){ // 日程模块加载方式
            const selectedUser = t.url.split('?')[1].split('&')[1].split('=')[1];
            this.state.weaWorkplanLoaded && window.weaWorkplan && window.weaWorkplan.com ?
            ifame = <window.weaWorkplan.com.MyWorkPlan ecId={`${this && this.props && this.props.ecId || ''}_undefined@ai7pco`} location={{query:{hidesidebar: 'true',hideheader: 'true', selectedUser:selectedUser, fromcard:'true'}}}/> 
            : 
            ''
          }else{
            ifame = <iframe className="card-iframe"  style={{height:window.innerHeight-175}} src={t.url}></iframe>
          }
        }
      }
    });
    return (
      <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@4jxjh8`} className={innerPage?'hrm-card-hastop' : 'hrm-card-notop'}>
      {isIframe ? ifame : children}
      </WeaNewScroll> 
    );
  }
  render() {
    const {
      hrmCard
    } = this.props;
    let {
      verified,
      isAdmin,
      info,
      tabInfo,
      tabKey,
      showPortraitSetting,
      uploadPortrailAuth,
      hasRight,
      userId,
      setState,
      updateSuccess,
      topRightMenus
    } = hrmCard;
    const rightMenu = topRightMenus && topRightMenus() || [];
    info = toJS(info);
    const portraitDefalut = '/messager/images/icon_m_wev8.jpg';
    if (window.location.href.indexOf("/spa/hrm/index_mobx.html") > -1) {
      if (info) {
        let lastname = info.lastname || '';
        document.title = lastname ? i18n.label.resourceCard() + '-' + lastname : i18n.label.resourceCard();
      }
    }
    if (verified) {
      if(hasRight){
        if (verified && isAdmin) {
          return (
            <SystemCard ecId={`${this && this.props && this.props.ecId || ''}_SystemCard@vmf9rw`} {...this.props} id={this.props.params.hrmId}/>
          )
        }
        if (verified && !isAdmin) {
          const avatarProps = {userId};
          if(info.requestParams) Object.assign(avatarProps, {requestParams: JSON.parse(info.requestParams)});
          return (
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@uojsrt`} datas={rightMenu} >
              <div style={{height:'100%'}}>
              <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@kadp5g`} />
              <div className='hrm-my-card' style={{height:"100%",background: '#ffff'}}>
                <div className="hrm-my-card-top-wapper" style={{height: 60}}>
                  {
                    !isEmpty(info) && <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@rwtu3g`} className={"hrm-my-card-top"}>
                      <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@lq1pi0`} span="24" className='hrm-my-card-top-title' style={{paddingLeft:14,paddingTop:7,height:'100%'}}>
                        {
                          info.shortname != null && info.shortname.trim().length > 0 ?
                          <div className='hrm-my-card-top-title-img hrm-my-card-top-title-shortname' onClick={showPortraitSetting}>{info.shortname}</div>
                          :
                          <span style={{paddingLeft:10,paddingRight:14, display:'inline-block'}}>
                            {/* <img className='hrm-my-card-top-title-img' src={info.messagerurl || portraitDefalut} alt="" onClick={showPortraitSetting}/> */}
                            <span className='hrm-my-card-top-avatar' style={{top: '-2px'}} onClick={showPortraitSetting}>
                              <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@m37dbo`}
                                // userId={userId}
                                {...avatarProps}
                                ref={result => {
                                  if(updateSuccess && result) {
                                    result.requestParams && result.requestParams(userId);
                                    setState({updateSuccess: false});
                                  }
                                }}
                              />
                            </span>
                          </span>
                        }
                        <span style={{display:'inline-block',verticalAlign:'top'}} className='hrm-my-card-top-title-info'>
                          <div style={{fontSize:14}}>
                            <span style={{paddingRight:5}}>{info.lastname} {info.workcode ? `(${info.workcode})` : ''}</span>
                            {
                              info.sex &&  <span className={info.sex.value=='1'?'icon-coms-women femaleColor':'icon-coms-men maleColor'} title={info.sex.name}></span>
                            }
                          </div>
                            {
                              info.orginfo ? 
                              <div className='orgInfo'
                                dangerouslySetInnerHTML={{__html:info.orginfo}}  /> 
                              :
                              <div className = 'orgInfo'>
                                &nbsp;
                              </div>
                            }
                        </span>
                      </Col>
                    </Row>
                  }
                  <TopButton ecId={`${this && this.props && this.props.ecId || ''}_TopButton@br79o7`}
                    buttons={hrmCard.topButtons && hrmCard.topButtons()}
                    buttonSpace={10}
                    showDropIcon={hrmCard.topShowDropIcon}
                    dropMenuDatas={hrmCard.topRightMenus && hrmCard.topRightMenus()}
                  />
                </div>
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@9d23zw`}
                  type='editable-inline'
                  keyParam='key'
                  datas={toJS(tabInfo)}
                  selectedKey={tabKey}
                  onChange={ v => { 
                    this.tabsOnChange(v);
                  }}
                />
                {this.getTabChildren()}
              </div>
              {uploadPortrailAuth && <PortraitSetting ecId={`${this && this.props && this.props.ecId || ''}_PortraitSetting@vck80h`} store={hrmCard}/>}
              </div>
            </WeaRightMenu>
          )
        }
      }else{
        return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@a7bbha`} >
          <div style={{color : '#000'}}>
              {i18n.message.authFailed()}
          </div>
      </WeaAlertPage>
        )
      }
    }
    return (<div></div>)
  }

  tabsOnChange(key) {
    const {
      hrmCard
    } = this.props;
    this.setState({rightMenu: []})
    hrmCard.setTopButtons(null);
    hrmCard.setTopRightMenus(null);
    hrmCard.setTopShowDropIcon(false);
    let {
      tabInfo
    } = hrmCard;
    hrmCard.changeTab(key);
    tabInfo = toJS(tabInfo);
    tabInfo && tabInfo.forEach((t) => {
      if (t.key === key && !t.isIframe) {
        this.context.router.push({
          pathname: t.pathname,
          query: {
            fromcard: true
          }
        })
      }
    })
  }
}
export default Main;